<?php
namespace Src\controller;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Src\utils\UserEnum;
use Src\utils\ResponseUtils;
use Src\utils\UserUtils;
use Src\config\Db;

class UserController
{
    private $db;

    public function __construct(Db $db)
    {
        $this->db = $db;
    }

    // 获取所有用户 (管理员)
    // get /users
    public function getAllUsers(ServerRequestInterface $request, ResponseInterface $response)
    {
        $users = $this->db->fetchAll("SELECT id, username, email, role, created_at FROM user where status = 'active'");
        return ResponseUtils::ok($response, $users);
    }

    public function getUsersPage(ServerRequestInterface $request, ResponseInterface $response)
    {
        // 获取用户
        $page = $request->getQueryParams()["page"] ?? 1;
        $pageSize = $request->getQueryParams()["pageSize"] ?? 10;
        $offset = ($page - 1) * $pageSize;
        $search = $request->getQueryParams()['search'] ?? '';
        $clauseSql = " FROM user u where u.status = 'active' ";
        if ($search && !empty($search)) {
            $clauseSql .= " AND u.username LIKE '%$search%' ";
        }
        $limitSql = " LIMIT $offset, $pageSize ";
        $selectSql = "SELECT id, username, email, role, status, created_at   $clauseSql $limitSql";
        $users = $this->db->fetchAll($selectSql);
        $totalCountSql = "SELECT COUNT(*) as count  " . $clauseSql;
        $totalCount = $this->db->fetch($totalCountSql)['count'];
        $data = [
            'code' => 200,
            'message' => '获取成功',
            'success' => true,
            'data' => [
                'total' => $totalCount,
                'page' => $page,
                'data' => $users,
                'pageSize' => $pageSize,
            ]
        ];
        return ResponseUtils::withJson($response, $data, 200);
    }

    // 获取单个用户信息
    public function getUser(ServerRequestInterface $request, ResponseInterface $response)
    {
        // 获取请求路径下的信息,比如 /user/{id}
        $userId = $request->getAttribute('user_id');
        $user = $this->db->fetch(
            "SELECT id, username, email, avatar, bio, created_at, role FROM user WHERE id = ?",
            [$userId]
        );

        if (!$user) {
            ResponseUtils::errorwithEnum($response, UserEnum::USER_NOT_FOUND);
        }

        // 获取用户发布的博客数量
        // $blogCount = 0;
        // $blogResult = $this->db->fetch(
        //     "SELECT COUNT(*) as count FROM blog WHERE user_id = ?",
        //     [$userId]
        // );
        // $user['blog_count'] = $blogResult['count'];
        return ResponseUtils::ok($response, $user);
    }

    // 更新用户信息
    public function updateUser(ServerRequestInterface $request, ResponseInterface $response)
    {
        $currentUser = UserUtils::getCurrentUser($request);
        $userId = $request->getAttribute('user_id');

        // 检查权限
        if ($currentUser->id != $userId && $currentUser->role != 'admin') {
            return ResponseUtils::errorWithEnum($response, UserEnum::PERMISSION_DENIED);
        }

        $data = $request->getParsedBody();
        $updateData = [];
        $params = [];

        if (isset($data['bio'])) {
            $updateData[] = "bio = ?";
            $params[] = $data['bio'];
        }

        if (isset($data['avatar'])) {
            $updateData[] = "avatar = ?";
            $params[] = $data['avatar'];
        }

        // 管理员可以更新角色
        if ($currentUser->role == 'admin' && isset($data['role'])) {
            $updateData[] = "role = ?";
            $params[] = $data['role'];
        }

        if (empty($updateData)) {
            return ResponseUtils::errorWithEnum($response, exceptionenum: UserEnum::USER_NOT_UPDATE);
        }
        $params[] = $userId;
        $sql = "UPDATE user SET " . implode(', ', $updateData) . " WHERE id = ?";

        $this->db->execute($sql, $params);


        return ResponseUtils::ok($response, ['message' => 'User updated successfully']);
    }

    // 删除用户 (管理员)
    // delete /user/{id}
    public function deleteUser(ServerRequestInterface $request, ResponseInterface $response)
    {
        $userId = $request->getAttribute('user_id');

        // 防止删除自己
        $currentUser = $request->getAttribute('user');
        if ($currentUser->id == $userId) {
            return ResponseUtils::errorWithEnum($response, UserEnum::CANNOT_DELETE_SELF);
        }

        $this->db->execute("DELETE FROM user WHERE id = ?", [$userId]);
        return ResponseUtils::ok($response, 'User deleted successfully');
    }
}
?>